<!--
  @文件名： ordinaryColumn
  @来源：YongPing.Wang|2023/08/21 17:03
  @描述：echart 组件底座  chartOption内必传series
-->
<template>
  <div class="ordinaryColumn" ref="renderOrdinaryRef">
    <div ref="ordinaryRef" style="width: 100%; height: 100%"></div>
  </div>
</template>

<script setup lang="ts">
  import * as echarts from 'echarts'
  import { nextTick, onBeforeUnmount, onMounted, ref, watch, markRaw, getCurrentInstance, type ComponentInternalInstance } from 'vue'

  const { proxy } = getCurrentInstance() as ComponentInternalInstance
  // 返回
  const emits = defineEmits([
    'getChartInstance', // 把实例返回 给 上一层
    'resizeChange', // 监听到页面大小变化
  ])
  const props = defineProps({
    // 图表数据
    chartOption: {
      type: Object,
    },
  })
  // 实例
  const chartInstance = ref<any>(null)
  const renderOrdinaryRef = ref<HTMLElement | null>(null)
  const ordinaryRef = ref<HTMLElement | null>(null)
  // 设置大小
  const chartResize = (): void => {
    if (renderOrdinaryRef.value) {
      proxy?.$erd.listenTo(renderOrdinaryRef.value, () => {
        emits('resizeChange')
        void nextTick(() => {
          chartInstance.value?.resize()
        })
      })
    }
  }
  // 创建
  const creatDraw = (): void => {
    if (ordinaryRef.value) {
      chartInstance.value = markRaw(echarts.init(ordinaryRef.value))
      chartInstance.value.setOption(props.chartOption)
      emits('getChartInstance', chartInstance.value)
    }
  }
  // 重置
  const resetDraw = (): void => {
    chartInstance.value.clear()
    chartInstance.value.setOption(props.chartOption)
    emits('getChartInstance', chartInstance.value)
  }

  // 初始化
  onMounted(() => {
    chartResize()
  })

  onBeforeUnmount(() => {
    if (renderOrdinaryRef.value) {
      proxy?.$erd.uninstall(renderOrdinaryRef.value)
    }
  })

  watch(
    () => props.chartOption,
    (newOptions: any) => {
      if (newOptions?.series) {
        if (chartInstance.value == null) {
          void nextTick(() => {
            creatDraw()
          })
        } else {
          resetDraw()
        }
      }
    },
    {
      deep: true,
    }
  )
</script>

<style scoped lang="scss">
  .ordinaryColumn {
    width: 100%;
    height: 100%;
  }
</style>
